const promise = new Promise(function(resolve,reject){
    if(true){
        resolve(value)
    }else{
        reject(error);
    }
})



promise.then(function(value){
    //success
},function(error){
    //failure
})

function timeout(ms){
    return new Promise((resolve,reject)=>{
        setTimeout(resolve,ms,'done')
    })
}

timeout(1000).then((value)=>{
    console.log('timeout',value)
})


var promise02 = new Promise(function(resolve, reject) {
    console.log('Promise02');
    resolve();
  });
  
  promise02.then(function() {
    console.log('Promise02 resolved.');
  });
  
  
  //异步加载图片
  function loadImageAsync(url) {
    return new Promise(function(resolve, reject) {
      const image = new Image();
  
      image.onload = function() {
        resolve(image);
      };
  
      image.onerror = function() {
        reject(new Error('Could not load image at ' + url));
      };
  
      image.src = url;
    });
  }

  /*
  const getJSON = function(url) {
    const promise = new Promise(function(resolve, reject){
      const handler = function() {
        if (this.readyState !== 4) {
          return;
        }
        if (this.status === 200) {
          resolve(this.response);
        } else {
          reject(new Error(this.statusText));
        }
      };
      const client = new XMLHttpRequest();
      client.open("GET", url);
      client.onreadystatechange = handler;
      client.responseType = "json";
      client.setRequestHeader("Accept", "application/json");
      client.send();
  

    });
  
    return promise;
  };
  
  getJSON("/posts.json").then(function(json) {
    console.log('Contents: ' + json);
  }, function(error) {
    console.error('出错了', error);
  });

  */

  /*
  const p1 = new Promise(function (resolve, reject) {
    console.log('p1...')
    setTimeout(() => reject(new Error('fail p1')), 3000)
  })
  
  const p2 = new Promise(function (resolve, reject) {
    console.log('p2...')
    setTimeout(() => resolve(p1), 100)
  })
  
  p2
    .then(result => {console.log(result)})
    .catch(error => {console.log(error)})

 

    new Promise((resolve, reject) => {
      resolve(1);
      console.log(2);
    }).then(r => {
      console.log(r);
    });
    
   */

    new Promise((resolve, reject) => {
      return resolve(1);
      // 后面的语句不会执行
      console.log(2);
    })


    // 写法一
const promise03 = new Promise(function(resolve, reject) {
  try {
    throw new Error('test03');
  } catch(e) {
    reject(e);
  }
});
promise03.catch(function(error) {
  console.log(error);
});

// 写法二
const promise04 = new Promise(function(resolve, reject) {
  reject(new Error('test04'));
});
promise04.catch(function(error) {
  console.log(error);
});